<template>
  <div class="todo-container">
    
    <div class="todo-wrap">
      <!-- <Top /> -->
      <TodoHeader :addTodo="addTodo" />
      <TodoMain :todolist="todolist" :delTodo="delTodo" :checkedTodo="checkedTodo" />
      <TodoFooter 
        v-show="todolist.length"
        :clearAllDoneOk="clearAllDoneOk"
        :todolist="todolist"
        :checkedAllTodo="checkedAllTodo"
       />
    </div>
  </div>
</template>

<script>
import TodoHeader from "@/components/TodoList/TodoHeader";
import TodoMain from "@/components/TodoList/TodoMain";
import TodoFooter from "@/components/TodoList/TodoFooter";
import { nanoid } from "nanoid";
export default {
  name: "TodoList",
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      todolist: JSON.parse(localStorage.getItem("todolist")) || []
    };
  },
  methods: {
    //添加一个todo
    addTodo(title) {
      //判断当前数据中是否存在要添加的数据
      let bol = this.todolist.some((item) => item.title === title);
      if (!bol) {
        //准备一个数据
        let newtodo = {
          id: nanoid(),
          title,
          done: false,
        };
        // 向数组添加新数据
        this.todolist.unshift(newtodo);

       

        return true;
      } else {
        return false;
      }
    },
    //删除一个todo
    delTodo(id) {
      if (window.confirm("确定删除吗？")) {
        //过滤新数组并赋值
        this.todolist = this.todolist.filter((item) => item.id !== id);
         

      }
    },
    //更新某个todo的完成
    checkedTodo(id,done){
        //更新某个todo  的 完成
        this.todolist.forEach(item => {
            if(item.id === id ){
                item.done = done;
            }
        })

         

    },
    //清除已完成
    clearAllDoneOk(){
      //过滤掉 完成的 并 直接赋值
      this.todolist = this.todolist.filter(item => !item.done);
    },
    //全选或取消全选
    checkedAllTodo(done){
        this.todolist.forEach(item => item.done = done);
    }
  },
  watch:{
    todolist:{
      deep:true,
      handler(){
         // 向本地存储添加数据
         localStorage.setItem("todolist",JSON.stringify(this.todolist));
    
      }
    }
  },
  //  进入组件时 路由守卫
  beforeRouteEnter(to,from,next){

    //在此时，不能访问 this.因为，先执行 组件内部的路由守卫，然后在创建组件对象。
    console.log(this);
      if(localStorage.getItem("token")){
        next()
      } else{
        next({
          path:"/login",
          query:{
            url:to.path
          }
        })
      }
  },
  //离开组件时路由守卫
  beforeRouteLeave(to,from,next){
    //  编写的内容为保存。
    if(window.confirm("确定要离开吗？未支付")){
        next();
    }
    
  }
 
  
};
</script>

<style scoped>
/*base*/
body {
  background: #fff;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>